package com.wu.creditmanager;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.wu.creditmanager.db.CreditsDbAdapter;
import com.wu.creditmanager.entity.Credit;
import com.wu.creditmanager.util.Constants;
import com.wu.creditmanager.util.ImageUtil;
import com.wu.creditmanager.util.LayoutUtil;

public class CreditGrid extends Activity {
	private static final int ACTIVITY_CREATE = 0;
	private static final int ACTIVITY_EDIT = 1;

	private static final String TAG = "CreditManager";

	private CreditsDbAdapter mDbHelper;
	private List<Credit> credits = new ArrayList<Credit>();
	private ListView gridView;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.credit_list_grid);
		LayoutUtil.initToolbar(this, R.string.account, null,
				R.string.btn_insert, new OnClickListener() {
					public void onClick(View v) {
						startActivityForResult(new Intent(CreditGrid.this,
								CreditEditor.class), ACTIVITY_CREATE);
					}
				});
		gridView = (ListView) findViewById(R.id.credit_grid);
		mDbHelper = new CreditsDbAdapter(this);
		loadCredit();
		gridView.setOnCreateContextMenuListener(this);
		registerForContextMenu(gridView);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Credit c = credits.get(position);
				Intent intent = new Intent(CreditGrid.this, CreditInfo.class);
				intent.putExtra(Credit.TAG, c.getId());
				startActivity(intent);
			}
		});
		gridView.setEmptyView(findViewById(android.R.id.empty));
		LayoutUtil.initAdLayout(this);
	}

	private void loadCredit() {
		mDbHelper.open();
		credits = mDbHelper.fetchAllCredits();
		mDbHelper.close();
		gridView.setAdapter(new CreditGrid.CreditAdapter(this));
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info;
		try {
			info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		} catch (ClassCastException e) {
			Log.e(TAG, "bad menuInfo", e);
			return false;
		}
		switch (item.getItemId()) {
		case Constants.MENU_CREDITEDIT:
			Intent intent = new Intent(this, CreditEditor.class);
			intent.putExtra(Credit.TAG, credits.get(info.position));
			startActivityForResult(intent, ACTIVITY_EDIT);
			break;
		case Constants.MENU_CREDITDELETE:
			Credit credit = credits.get(info.position);
			mDbHelper.open(true);
			mDbHelper.deleteCredit(credit.getId());
			mDbHelper.close();
			loadCredit();
			AlarmListWidget.update(this);
			break;
		}
		return super.onContextItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterView.AdapterContextMenuInfo info;
		try {
			info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		} catch (ClassCastException e) {
			Log.e(TAG, "bad menuInfo", e);
			return;
		}
		menu.setHeaderTitle(credits.get(info.position).getName());
		menu.add(0, Constants.MENU_CREDITEDIT, 0, R.string.menu_edit);
		menu.add(0, Constants.MENU_CREDITDELETE, 0, R.string.menu_delete);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		super.onActivityResult(requestCode, resultCode, data);
		Bundle extras = data.getExtras();
		Credit credit = (Credit) extras.getSerializable(Credit.TAG);
		switch (requestCode) {
		case ACTIVITY_CREATE:
			mDbHelper.open(true);
			mDbHelper.createCredit(credit);
			mDbHelper.close();
			loadCredit();
			AlarmListWidget.update(this);
			break;
		case ACTIVITY_EDIT:
			mDbHelper.open(true);
			mDbHelper.updateCredit(credit.getId(), credit);
			mDbHelper.close();
			AlarmListWidget.update(this);
			loadCredit();
			break;
		default:
			break;
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case Constants.MENU_ABOUT:
			return new AlertDialog.Builder(this)
					.setIcon(R.drawable.icon)
					.setTitle(R.string.dialog_about_header)
					.setMessage(R.string.dialog_about)
					.setPositiveButton(R.string.btn_OK,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
								}
							}).create();
		default:
			return null;
		}
	}

	@Override
	protected void onDestroy() {
		mDbHelper.close();
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		loadCredit();
	}

	private class CreditAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public CreditAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return credits.size();
		}

		public Object getItem(int position) {
			return credits.get(position % credits.size());
		}

		public long getItemId(int position) {
			return credits.get(position % credits.size()).getId();
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.credit_list_grid_cell,
						null);
				holder = new ViewHolder();
				holder.name = (TextView) convertView
						.findViewById(R.id.cell_text);
				holder.bank = (TextView) convertView
						.findViewById(R.id.cell_text_bank);
				holder.icon = (ImageView) convertView
						.findViewById(R.id.cell_icon);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final Credit info = credits.get(position % credits.size());
			holder.name.setText(info.getName());
			holder.bank.setText(info.getBank().getName());
			if (info.getIcon() != null) {
				ImageUtil.setImage(info.getIcon(), holder.icon);
			} else {
				holder.icon.setImageResource(info.getBank().getIconResId());
			}
			return convertView;
		}

		class ViewHolder {
			TextView name;
			TextView bank;
			ImageView icon;
		}

	}
}